from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from rest_framework.response import Response
from rest_framework.views import APIView

# https://www.django-rest-framework.org/api-guide/views/

class SimpleAPIView(APIView):
    # http -v  http://127.0.0.1:8000/tutorial/param/23/
    def get(self, request, param, *args, **kwargs):
        return Response({'param': param})

    # http -v  PUT http://127.0.0.1:8000/tutorial/param/23/?param1=hello&param2=world
    def put(self, request, *args, **kwargs):
        param1 = request.query_params.get('param1')
        param2 = request.query_params.get('param2', 'default_value')  # 提供默认值
        return Response({'param1': param1, 'param2': param2})


class JSONDataAPIView(APIView):

    # http -v  POST http://127.0.0.1:8000/tutorial/create  username=mingcai password=123456
    # 对于 POST、PUT、PATCH 请求，可以使用 request.data 获取请求体中的数据。
    def post(self, request, *args, **kwargs):
        data = request.data
        return Response({'received_data': data})


class MyAPIView(APIView):
    # http -v  http://127.0.0.1:8000/tutorial/code/2023/java/
    def get(self, request, param1, param2, *args, **kwargs):
        # 处理路径参数
        return Response({'param1': param1, 'param2': param2})


class ArticleListView(APIView):
    # http http://localhost:8000/tutorial/articles/2023/04/
    def get(self, request, year, month, *args, **kwargs):
        # 处理请求
        articles = [
            {'title': 'Article 1', 'content': 'Content of article 1'},
            {'title': 'Article 2', 'content': 'Content of article 2'},
        ]
        return Response({'year': year, 'month': month, 'articles': articles})


class HtmlReportView(APIView):
    def put(self, request):
        html = render_to_string(template_name='tutorial/index.html')
        return HttpResponse(html)

    def get(self, request):
        return render(request, 'tutorial/index.html')
